/**
 * @a https://leetcode.cn/problems/permutations-ii/
 */

#include "../common.h"

class Solution {
private:
    vector<vector<int>> ret;

public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<int> tmp(nums.begin(), nums.end());
        dfs(tmp, 0);
        return ret;
    }
    void dfs(vector<int>& nums, int index) {
        if (index == nums.size() - 1) {
            ret.push_back(nums);
            return;
        }
        set<int> registry; // 不能是全局必须随 index 增长而增长
        for (int i = index; i < nums.size(); i++) {
            if (registry.find(nums[index]) != registry.end())
                continue; // dedupe
            registry.insert(nums[i]);
            swap(nums[index], nums[i]);
            dfs(nums, index + 1);
            swap(nums[index], nums[i]);
        }
    }
};